package com.envper.handler;

import com.envper.mysql.domain.Result;
import com.envper.mysql.domain.Status;
import com.envper.common.exception.GlobalException;
import jakarta.servlet.http.HttpServletRequest;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

@RestControllerAdvice
@Slf4j
@RequiredArgsConstructor
public class ServiceExceptionHandler {
    private final HttpServletRequest request;

    @ExceptionHandler(GlobalException.class)
    public Result<String> globalException(GlobalException exception) {
        if(!ObjectUtils.isEmpty(exception.getLogger()))
            exception.getLogger().error("对于来自{} {}的请求,返回{},错误信息为：{}", request.getLocalAddr(), request.getRequestURI(), exception.getCode(), exception.getMessage());
        return Result.fail(exception.getCode(), exception.getMessage());
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Result<String> methodArgumentNotValidException(MethodArgumentNotValidException exception) {
        return Result.fail(Status.PARAMERROR);
    }
}
